{include file="public/layout" /}

<body>
<script type="text/javascript" src="__SKIN__/js/jquery-ui/jquery-ui.min.js?v={$version}"></script>
<div class="layui-fluid " id="LAY-component-layer-list">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card web-system">
                <div class="layui-card-body layui-form">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><b>*</b>广告名称</label>
                        <div class="layui-input-inline">
                            <input type="text" name="title" id="title" value="" lay-verify="required" class="layui-input">
                        </div>
                        <div class="layui-input-inline layui-form-mid layui-word-aux ey_helptips"></div>
                        <div class="layui-form-inline2 ey_helptips_txt none" style="display: none;">保持唯一性，不可重复</div>
                    </div>
                    <div class="layui-form-item ">
                        <label class="layui-form-label">广告内容</label>
                        <div class="layui-input-inline">
                            <div class="upload-box">
                              <div class="upload-right fl">
                                <button class="layui-btn multi-upload-demoMore layui-btn-primary layui-btn-sm fl mb10 mr5" lay-data="{number:100,ey_savepath:'allimg',ey_callback:'imgupload_call_back'}"><i class="layui-icon">&#xe67c;</i>上传图片</button>
                                <button class="layui-btn layui-btn-sm layui-btn-primary layui-btn-sm fl mb10" onClick="GetPictureFolder(100,'litpic_local','imgupload_call_back');"><i class="layui-icon">&#xe64a;</i>图库</button>
                              </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">区域广告</label>
                        <div class="layui-input-inline">
                            <input type="hidden" id="province_id" value="0"/>
                            <input type="hidden" id="city_id" value="0"/>
                            <input type="hidden" id="area_id" value="0"/>
                            <input type="hidden" id="counts" value="0"/>
                            <input type="hidden" id="region_name" value="不限区域"/>
                            <span id="region_span" onclick="selectRegion()">不限区域</span>
                        </div>
                    </div>
                    <div class="layui-form-item none" id="imgupload_list">
                        <label class="layui-form-label"></label>
                        <div class="edit-box-con2 fl sort-list">
                            <div class="images-upload" style="display: none;"></div>
                            <!-- 上传图片显示的样板 start -->
                            <div class="images_upload_tpl" style="display: none;">
                                <div class="images-upload">
                                    <div class="upimg">
                                        <div class="icaction" style="display: none;">
                                            <span class="load_images">
                                                <a href="javascript:void(0);" style="color:white">
                                                    <i class="layui-icon layui-icon-search mr5"></i>查看大图
                                                </a>
                                            </span>
                                        </div>
                                        <div class="cover-bg" style="display: none"></div>
                                        <img src="__STATIC__/admin/images/add-button.jpg">
                                    </div>
                                    <input type="hidden"/>
                                    <span class="span_input">
                                        <input type="hidden"/>
                                        <input type="hidden"/>
                                        <input type="hidden"/>
                                        <input type="hidden"/>
                                    </span>
                                    <textarea placeholder="请输入标题..." style="height: 28px;"></textarea>
                                    <textarea placeholder="请输入链接网址..." style="height: 28px;"></textarea>
                                    <textarea placeholder="广告注释：支持HTML代码" style="height: 64px;"></textarea>
                                    <div class="operation">
                                        <a href="javascript:void(0);"></a>
                                        <a href="javascript:void(0);"></a>
                                        <a href="javascript:void(0);"></a>
                                        <a href="javascript:void(0);"></a>
                                    </div>
                                </div>
                            </div>
                            <!-- 上传图片显示的样板 end -->
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block">

                            <button class="layui-btn" lay-submit lay-filter="formSubmit">确认提交</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // 勾选新窗口打开链接
    function CheckedTarget(t){
        if ($(t).is(':checked')) {
            $(t).parent().find('input[name="img_target[]"]').val(1);
        }else{
            $(t).parent().find('input[name="img_target[]"]').val(0);
        }
    }

    // 鼠标事件，加载查看大图和更新图片
    $(document).ready(function(){
        $(".upimg").live('mouseover', function(){
            $(this).find('div.icaction').show();
            $(this).find('div.cover-bg').show();
        }).live('mouseout', function(){
            $(this).find('div.icaction').hide();
            $(this).find('div.cover-bg').hide();
        });
    });

    // 查看大图
    function Images(links){
        var max_width = 650;
        var max_height = 350;
        var img = "<img src='"+links+"'/>";
        $(img).load(function() {
            width  = this.width;
            height = this.height;
            if (width > height) {
                if (width > max_width) {
                    width = max_width;
                }
                width += 'px';
            } else {
                width = 'auto';
            }
            if (width < height) {
                if (height > max_height) {
                    height = max_height;
                }
                height += 'px';
            } else {
                height = 'auto';
            }

            var links_img = "<img style='width:"+width+";height:"+height+";' src="+links+">";

            layer.open({
                type: 1,
                title: false,
                closeBtn: true,
                area: [width, height],
                skin: 'layui-layer-nobg', //没有背景色
                content: links_img
            });
        });
    }

    layui.config({
        base: '__SKIN__/' //静态资源所在路径
        ,version: '{$version}'
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'form',  'upload'], function(){
        var $ = layui.$
            ,upload = layui.upload
            ,form = layui.form;
        //监听提交
        form.on('submit(formSubmit)', function(data){
            var load = layer_loading();
            data.field._ajax = 1;
            $.ajax({
                type : 'post',
                url : "{:url('AdPosition/add')}",
                data : data.field,
                dataType : 'json',
                success : function(res){
                    layer.close(load); //关闭loading
                    if(res.code == 1){
                        layer.msg(res.msg, {icon: 1, time: 1000}, function(){
                            parent.gourl(res.url);
                        });
                    }else{
                        layer.msg(data.msg, {icon: 2,time: 2000});
                    }
                },
                error: function(e){
                    layer.close(load); //关闭loading
                    showErrorAlert();
                }
            });
            return false;
        });
    });
    // 代码调用js
    function copyToClipBoard(id) {
        var adstr = "{eju:ad aid='" + id + "'}\r\n   <a href='{$"+"field.links}' {$"+"field.target}><img src='{$"+"field.litpic}' alt='{$"+"field.title}' /></a>\r\n{/eju:ad";
        var contentdiv = '<div class="dialog_content" style="margin: 0px; padding: 0px;"><dl style="padding:10px 30px;line-height:30px"><dd>标签 ad 调用:</dd>'
        contentdiv += '<textarea rows="4" cols="60" style="width:400px;height:80px;">' + adstr + '}</textarea>'
        contentdiv += '<dd style="border-top: dotted 1px #E7E7E7; color: #F60;">请将对应标签代码复制并粘贴到对应模板文件中！</dd></dl></div>'
        layer.open({
            title: '代码调用',
            type: 1,
            skin: 'layui-layer-demo',
            area: ['480px', '240px'], //宽高
            content: contentdiv
        });
    }
    // 上传图集相册回调函数
    function imgupload_call_back(pathObj){
        if (Array.isArray(pathObj)){
            var paths = pathObj;
        }else{
            var paths = [pathObj.url];
        }
        $('#imgupload_list').show();
        var province_id = $("#province_id").val();
        var city_id = $("#city_id").val();
        var area_id = $("#area_id").val();
        var region = 0;
        if (area_id > 0){
            region = area_id;
        }else if (city_id > 0){
            region = city_id;
        }else if (province_id > 0){
            region = province_id;
        }
        var counts = $("#counts").val();
        var region_name = $("#region_name").val();
        var last_div = $(".images_upload_tpl").html();
        var inputs   = $('.span_input input');
        for (var i=0;i<paths.length ;i++){
            $(".images-upload:eq(0)").before(last_div);  // 插入一个 新图片
            $(".images-upload:eq(0)").addClass("region"+region);
            // 修改他的链接地址
            $(".images-upload:eq(0)").find('span:eq(0)').attr('onclick',"Images('"+paths[i]+"');");
            // 修改他的图片路径
            $(".images-upload:eq(0)").find('img').attr('src',paths[i]);
            // 处理图片路径及隐藏域
            if (inputs.length > '0') {
                // 修改隐藏域，提交ID隐藏域
                $(".images-upload:eq(0)").find('input:eq(0)').attr('name','img_id[]').attr('value','');
                // 修改隐藏域，提交图片隐藏域
                $(".span_input:eq(0)").find('input:eq(0)').attr('name','img_litpic[]').attr('value',paths[i]);
                $(".span_input:eq(0)").find('input:eq(1)').attr('name','province_id[]').attr('value',province_id);
                $(".span_input:eq(0)").find('input:eq(2)').attr('name','city_id[]').attr('value',city_id);
                $(".span_input:eq(0)").find('input:eq(3)').attr('name','area_id[]').attr('value',area_id);
                // 提交标题
                $(".images-upload:eq(0)").find('textarea:eq(0)').attr('name','img_title[]');
                // 提交跳转链接
                $(".images-upload:eq(0)").find('textarea:eq(1)').attr('name','img_links[]');
                //提交广告简介
                $(".images-upload:eq(0)").find('textarea:eq(2)').attr('name','intro[]');
                // 提交新窗口选项
                $(".images-upload:eq(0)").find('div.operation a:eq(0)').html("<label><input lay-ignore type='checkbox' title='在新窗口打开' onclick='CheckedTarget(this)'/>新窗口<input type='hidden' name='img_target[]' value='0'></label>");
                //标签调用
                $(".images-upload:eq(0)").find('div.operation a:eq(1)').attr('onclick',"copyToClipBoard('广告ID')").html("<i class='layui-icon layui-icon-fonts-code mr5'></i>标签调用");
                //区域名称
                $(".images-upload:eq(0)").find('div.operation a:eq(2)').attr('onclick',"changeRegion(this)").html("<i class='layui-icon layui-icon-fonts-code mr5'></i>"+region_name);
                // 删除按钮
                $(".images-upload:eq(0)").find('div.operation a:eq(3)').attr('onclick',"ClearPicArr(this,'"+paths[i]+"')").html("<i class='layui-icon layui-icon-close mr5'></i>删除");
            }
            $(".region"+region).show();
        }
        counts = parseInt(counts) + paths.length;
        $("#counts").val(counts);
        $("#region_span").html(region_name+"("+counts+")");
    }
    //点击弹出选中区域（弹窗）
    var select_region;
    function selectRegion() {
        var province_arr = new Array();
        var city_arr =new Array();
        var area_arr = new Array();
        $("input[name^='province_id']").each(function(i){
            province_arr.push(this.value);
        });
        $("input[name^='city_id']").each(function(i){
            city_arr.push(this.value);
        });
        $("input[name^='area_id']").each(function(i){
            area_arr.push(this.value);
        });
        select_region = layer.open({
            type : 2,
            title : '选择区域',
            area : ['700px','500px'],
            shade : 0.2,
            iframeAuto:true,
            content : "{:url('AdPosition/ajaxSelectRegion')}"+'&province='+province_arr.join()+'&city='+city_arr.join()+'&area='+area_arr.join()+'&func=select_region_back',
            end : function(){
            }
        });
    }
    //选中区域(赋值)
    function select_region_back(recall) {
        $("#province_id").val(recall.province_id);
        $("#city_id").val(recall.city_id);
        $("#area_id").val(recall.area_id);
        $("#counts").val(recall.counts);
        $("#region_name").val(recall.name);
        $("#region_span").html(recall.name+"("+recall.counts+")");
        $(".images-upload").hide();
        $(".region"+recall.id).show();
        layer.close(select_region);
    }
    
    //修改区域(弹窗)
    var region_open;
    var region_obj;
    function changeRegion(obj){
        region_obj = obj;
        var province_arr = new Array();
        var city_arr =new Array();
        var area_arr = new Array();
        $("input[name^='province_id']").each(function(i){
            province_arr.push(this.value);
        });
        $("input[name^='city_id']").each(function(i){
            city_arr.push(this.value);
        });
        $("input[name^='area_id']").each(function(i){
            area_arr.push(this.value);
        });
        region_open = layer.open({
            type : 2,
            title : '变更区域',
            area : ['700px','500px'],
            shade : 0.2,
            iframeAuto:true,
            content : "{:url('AdPosition/ajaxSelectRegion')}"+'&province='+province_arr.join()+'&city='+city_arr.join()+'&area='+area_arr.join()+'&func=set_region_back',
            end : function(){
            }
        });
    }
    //修改区域（赋值）
    function set_region_back(recall) {
        var parent_obj = $(region_obj).parent().parent();
        var province_id = parent_obj.find('.span_input:eq(0)').find('input:eq(1)').val();
        var city_id = parent_obj.find('.span_input:eq(0)').find('input:eq(2)').val();
        var area_id = parent_obj.find('.span_input:eq(0)').find('input:eq(3)').val();
        var region_name =  parent_obj.find('div.operation a:eq(2)').html();

        if (region_name != recall.name){
            parent_obj.find('.span_input:eq(0)').find('input:eq(1)').val(recall.province_id);
            parent_obj.find('.span_input:eq(0)').find('input:eq(2)').val(recall.city_id);
            parent_obj.find('.span_input:eq(0)').find('input:eq(3)').val(recall.area_id);
            parent_obj.find('div.operation a:eq(2)').html(recall.name);
            parent_obj.removeClass().addClass("images-upload region"+recall.id);
            parent_obj.hide();
            var counts = $("#counts").val();
            counts = parseInt(counts) -1;
            var region_name_all = $("#region_name").val();
            $("#counts").val(counts);
            $("#region_span").html(region_name_all+"("+counts+")");
        }
        layer.close(region_open);
    }
    // 上传之后删除组图input
    function ClearPicArr(obj,path)
    {
        $(obj).parent().parent().remove(); // 删除完服务器的, 再删除 html上的图片
        $.ajax({
            type:'POST',
            url:"{:url('Uploadify/delupload')}",
            data:{action:"del", filename:path},
            success:function(){
                var counts = $("#counts").val();
                counts = parseInt(counts) -1;
                var region_name_all = $("#region_name").val();
                $("#counts").val(counts);
                $("#region_span").html(region_name_all+"("+counts+")");
            }
        });
    }
    // 图集相册的拖动排序相关 js
    $( ".sort-list" ).sortable({
        start: function( event, ui) {

        }
        ,stop: function( event, ui ) {

        }
    });
    $( ".sort-list" ).disableSelection();

</script>
{include file="public/footer" /}
